<template>
    <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
                class="-mb-15px"
                :model="queryParams"
                ref="queryFormRef"
                :inline="true"
                label-width="68px"
        >
            <!-- 接口名称搜索项 -->
            <el-form-item label="接口名称" prop="interfaceName">
                <el-input
                        v-model="queryParams.interfaceName"
                        placeholder="请输入接口名称"
                        clearable
                        @keyup.enter="handleQuery"
                        class="!w-240px"
                />
            </el-form-item>
            <el-form-item label="接口方法" prop="interfaceMethod">
                <el-select
                        v-model="queryParams.interfaceMethod"
                        placeholder="请选择接口类型"
                        clearable
                        class="!w-240px"
                >
                    <el-option
                            v-for="dict in getStrDictOptions(DICT_TYPE.JIEKOU_TYPE)"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <!-- 状态搜索项 -->
            <el-form-item label="状态" prop="status">
                <el-select
                        v-model="queryParams.status"
                        placeholder="请选择状态"
                        clearable
                        class="!w-240px"
                >
                    <el-option
                            v-for="dict in getStrDictOptions(DICT_TYPE.INFOR_STATUS)"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="接口编码" prop="interfaceCode">
                <el-input
                        v-model="queryParams.interfaceCode"
                        placeholder="请输入接口编码"
                        clearable
                        @keyup.enter="handleQuery"
                        class="!w-240px"
                />
            </el-form-item>
            <el-form-item>
                <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
                <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
                <el-button type="primary" plain @click="openForm('create')">
                    <Icon icon="ep:plus" class="mr-5px" /> 新增
                </el-button>
                <el-button
                        type="danger"
                        plain
                        :disabled="isEmpty(checkedIds)"
                        @click="handleDeleteBatch"
                        v-hasPermi="['base:info:delete']"
                >
                    <Icon icon="ep:delete" class="mr-5px" /> 批量删除
                </el-button>
            </el-form-item>
        </el-form>
    </ContentWrap>

  <!-- 列表 -->
    <ContentWrap>
        <el-table
                row-key="id"
                v-loading="loading"
                :data="list"
                :stripe="true"
                :show-overflow-tooltip="true"
                @selection-change="handleRowCheckboxChange"
                style="width: 100%"
        >
            <!-- 序号列 -->
            <el-table-column label="序号" align="center">
                <template #default="scope">
                    {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>

            <!-- 接口名称列 -->
            <el-table-column label="接口名称" align="center" prop="interfaceName" />
            <el-table-column label="服务地址" align="center" prop="serviceUrl" />
            <el-table-column label="接口路径" align="center" prop="interfacePath" />
            <el-table-column label="接口类型" align="center" prop="interfaceType" />
            <el-table-column label="接口方法" align="center" prop="interfaceMethod">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.JIEKOU_TYPE" :value="scope.row.interfaceMethod.toString()" />
                </template>
            </el-table-column>
            <el-table-column label="接口编码" align="center" prop="interfaceCode" />
            <el-table-column label="Content-Type类型" align="center" prop="contentType" />
            <el-table-column label="请求示例" align="center">
                <template #default="scope">
                    <el-button link type="primary" @click="showJsonDialog('请求示例', scope.row.requestExample)">
                        查看
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="响应示例" align="center">
                <template #default="scope">
                    <el-button link type="primary" @click="showJsonDialog('响应示例', scope.row.responseExample)">
                        查看
                    </el-button>
                </template>
            </el-table-column>
            <!-- 申请次数 -->
            <el-table-column label="申请次数" align="center">
                <template #default="scope">
                    {{ scope.row.numberOfApplications.toString() }}
                </template>
            </el-table-column>
            <el-table-column
                    label="创建时间"
                    align="center"
                    prop="createTime"
                    :formatter="dateFormatter"
            />
            <!-- 状态列 - 0为上架，1为下架 -->
            <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.INFOR_STATUS" :value="scope.row.status" />
                </template>
            </el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作" align="center" min-width="200">
                <template #default="scope">
                    <el-button link type="primary" @click="openForm('update', scope.row.id)">
                        编辑
                    </el-button>
                    <!-- 上架/下架按钮 - 0为上架，1为下架 -->
                    <el-button
                            link
                            :type="scope.row.status === '0' ? 'warning' : 'success'"
                            @click="handlePublishStatusChange(scope.row)"
                    >
                        {{ scope.row.status === '0' ? '下架' : '上架' }}
                    </el-button>
                    <el-button
                            link
                            type="danger"
                            @click="handleDelete(scope.row.id)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
                :total="total"
                v-model:page="queryParams.pageNo"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />
    </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
    <InfoForm ref="formRef" @success="getList" />

  <!-- JSON查看弹窗 -->
    <el-dialog v-model="jsonDialogVisible" :title="jsonDialogTitle" width="800px">
        <el-input
                v-model="jsonContent"
                type="textarea"
                :rows="20"
                readonly
                placeholder="暂无数据"
        />
        <template #footer>
            <el-button @click="jsonDialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="copyJson">复制</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import { InfoApi, Info } from '@/api/base/info'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import InfoForm from './InfoForm.vue'

/** 基础信息 列表 */
defineOptions({ name: 'Info' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Info[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
// 查询参数
const queryParams = reactive({
    pageNo: 1,
    pageSize: 10,
    serviceUrl: undefined,
    interfacePath: undefined,
    interfaceType: undefined,
    interfaceMethod: undefined,
    interfaceCode: undefined,
    contentType: undefined,
    createTime: [],
    remark: undefined,
    interfaceName: undefined,
    status: undefined
})
const queryFormRef = ref() // 搜索的表单

// JSON查看相关
const jsonDialogVisible = ref(false)
const jsonDialogTitle = ref('')
const jsonContent = ref('')

/** 显示JSON对话框 */
const showJsonDialog = (title: string, content: string) => {
    jsonDialogTitle.value = title
    jsonContent.value = content ? formatJson(content.toString()) : '暂无数据'
    jsonDialogVisible.value = true
}

/** 格式化JSON */
const formatJson = (jsonStr: string) => {
    try {
        if (!jsonStr) return '暂无数据'
        const jsonObj = JSON.parse(jsonStr)
        return JSON.stringify(jsonObj, null, 2)
    } catch (e) {
        return jsonStr
    }
}

/** 复制JSON */
const copyJson = async () => {
    try {
        await navigator.clipboard.writeText(jsonContent.value)
        message.success('复制成功')
    } catch (err) {
        message.error('复制失败')
    }
}

/** 查询列表 */
const getList = async () => {
    loading.value = true
    try {
        const data = await InfoApi.getInfoPage(queryParams)
        list.value = data.list
        total.value = data.total
    } finally {
        loading.value = false
    }
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
    formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
    try {
        await message.delConfirm()
        await InfoApi.deleteInfo(id)
        message.success(t('common.delSuccess'))
        await getList()
    } catch {}
}

/** 批量删除基础信息 */
const handleDeleteBatch = async () => {
    try {
        await message.delConfirm()
        await InfoApi.deleteInfoList(checkedIds.value)
        checkedIds.value = []
        message.success(t('common.delSuccess'))
        await getList()
    } catch {}
}

/** 上下架状态切换操作 - 0为上架，1为下架 */
const handlePublishStatusChange = async (row: Info) => {
    // 状态逻辑调整：0表示上架，1表示下架
    const newStatus = row.status === '0' ? '1' : '0';
    const actionText = newStatus === '0' ? '上架' : '下架';

    try {
        await message.confirm(`确定要${actionText}该接口吗？`);
        await InfoApi.updateInfoStatus({
            ...row,
            status: newStatus
        });
        message.success(`${actionText}成功`);
        getList();
    } catch (err) {
        console.error(`更新状态失败:`, err);
    }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Info[]) => {
    checkedIds.value = records.map((item) => item.id)
}

/** 初始化 **/
onMounted(async () => {
    getList()
})
</script>
